package com.leicx.guli.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leicx.guli.common.enums.GuliExceptionEnum;
import com.leicx.guli.common.exception.RRException;
import com.leicx.guli.common.utils.HttpUtils;
import com.leicx.guli.common.utils.PageUtils;
import com.leicx.guli.common.utils.Query;
import com.leicx.guli.member.dao.MemberDao;
import com.leicx.guli.member.entity.MemberEntity;
import com.leicx.guli.member.entity.MemberLevelEntity;
import com.leicx.guli.member.service.MemberLevelService;
import com.leicx.guli.member.service.MemberService;
import com.leicx.guli.member.vo.MemberLoginVo;
import com.leicx.guli.member.vo.MemberRegisterVo;
import com.leicx.guli.member.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


@Service
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Resource
    MemberLevelService memberLevelService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity entity = new MemberEntity();

        MemberLevelEntity memberLevelEntity = memberLevelService.getDefaultLevel();
        entity.setLevelId(memberLevelEntity.getId());
        // 检查用户名和手机号是否唯一
        checkPhoneUnique(vo.getPhone());
        entity.setMobile(vo.getPhone());
        checkUsernameUnique(vo.getUserName());
        entity.setUsername(vo.getUserName());
        entity.setNickname(vo.getUserName());
        // 密码加密
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encodePwd = passwordEncoder.encode(vo.getPassword());
        entity.setPassword(encodePwd);

        // 保存
        this.baseMapper.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0) {
            throw new RRException(GuliExceptionEnum.PHONE_EXIST);
        }
    }

    @Override
    public void checkUsernameUnique(String username) {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", username));
        if (count > 0) {
            throw new RRException(GuliExceptionEnum.USERNAME_EXIST);
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo vo) {
        // 1.数据库查询
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>()
                .eq("username", vo.getLoginacct())
                .or()
                .eq("mobile", vo.getLoginacct()));
        if (Objects.isNull(entity)) {
            return null;
        } else {
            // 2.密码匹配
            String passwordDb = entity.getPassword();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            if (passwordEncoder.matches(vo.getPassword(), passwordDb)) {
                return entity;
            } else {
                return null;
            }
        }
    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        // 登录和注册
        String uid = socialUser.getUid();
        MemberEntity memberEntity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("uid", uid));
        if (Objects.nonNull(memberEntity)) {
            // 这个用户已经注册过
            MemberEntity update = new MemberEntity();
            update.setId(memberEntity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());
            this.baseMapper.updateById(update);
            memberEntity.setAccessToken(socialUser.getAccess_token());
            memberEntity.setExpiresIn(socialUser.getExpires_in());
            return memberEntity;
        } else {
            // 注册一个用户
            MemberEntity insert = new MemberEntity();
            try {
                // 查询当前社交用户的个人信息
                Map<String, String> query = new HashMap<>();
                query.put("access_token", socialUser.getAccess_token());
                query.put("uid", socialUser.getUid());
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<>(), query);
                if (response.getStatusLine().getStatusCode() == 200) {
                    String json = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSON.parseObject(json, JSONObject.class);
                    // 昵称
                    String name = (String) jsonObject.get("name");
                    insert.setNickname(name);
                    insert.setUsername(name);
                    // 性别
                    String gender = (String) jsonObject.get("gender");
                    insert.setGender(Objects.equals(gender, "m") ? 1 : 0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            insert.setAccessToken(socialUser.getAccess_token());
            insert.setExpiresIn(socialUser.getExpires_in());
            insert.setUid(socialUser.getUid());
            this.baseMapper.insert(insert);
            return insert;
        }
    }
}